using Microsoft.AspNetCore.Mvc;
using AdminSG3L.Applicaticn.ServicesInterface;
using AdminSG3L.Domain.Entities;
using AdminSG3L.Applicaticn.Commands;
using Serilog;
using AdminSG3L.Applicaticn.Dtos;
using Microsoft.AspNetCore.Authorization;

namespace AdminSG3L.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class PermissionController(IPermissionService permissionService) : ControllerBase
{
    private readonly IPermissionService _permissionService = permissionService;

    [HttpGet("{id}")]
    public async Task<ApiResponse<PermissionDto?>> GetById(Guid id)
    {
        try
        {
            return await _permissionService.GetDtoByIdAsync(id);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.GetById异常，Id={PermissionId}", id);
            return ApiResponse<PermissionDto?>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost]
    public async Task<ApiResponse<PermissionDto>> Create([FromBody] CreatePermissionDto dto)
    {
        try
        {
            return await _permissionService.CreateAsync(dto);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.Create异常，Permission={Permission}", dto);
            return ApiResponse<PermissionDto>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("batch")]
    public async Task<ApiResponse<IEnumerable<PermissionDto>>> BatchCreate([FromBody] IEnumerable<CreatePermissionDto> dtos)
    {
        try
        {
            return await _permissionService.BatchCreateAsync(dtos);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.BatchCreate异常");
            return ApiResponse<IEnumerable<PermissionDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPut("{id}")]
    public async Task<ApiResponse<bool>> Update(Guid id, [FromBody] CreatePermissionDto createDto)
    {
        try
        {
            // 从路径参数和请求体构建UpdatePermissionDto
            var updateDto = new UpdatePermissionDto(
                id,
                createDto.PermissionName,
                createDto.PermissionCode,
                createDto.Description,
                createDto.IsActive,
                createDto.ParentId
            );
            return await _permissionService.UpdateAsync(updateDto);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.Update异常，Id={PermissionId}", id);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpDelete("{id}")]
    public async Task<ApiResponse<bool>> Delete(Guid id)
    {
        try
        {
            return await _permissionService.DeleteAsync(id);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.Delete异常，Id={PermissionId}", id);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpDelete("{id}/cascade")]
    public async Task<ApiResponse<int>> DeleteCascade(Guid id)
    {
        try
        {
            return await _permissionService.DeleteCascadeAsync(id);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.DeleteCascade异常，Id={PermissionId}", id);
            return ApiResponse<int>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("batch-delete")]
    public async Task<ApiResponse<int>> BatchDelete([FromBody] IEnumerable<Guid> ids)
    {
        try
        {
            return await _permissionService.BatchDeleteAsync(ids);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.BatchDelete异常");
            return ApiResponse<int>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet]
    public async Task<ApiResponse<IEnumerable<PermissionDto>>> GetAll()
    {
        try
        {
            return await _permissionService.GetAllDtoAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.GetAll异常");
            return ApiResponse<IEnumerable<PermissionDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet("paged")]
    public async Task<ApiResponse<object>> GetPaged(int pageIndex, int pageSize, [FromQuery] string? name = null, [FromQuery] string? code = null, [FromQuery] int? status = null, [FromQuery] Guid? parentId = null)
    {
        try
        {
            // 构建筛选条件
            var filter = new PermissionFilterDto
            {
                Name = name,
                Code = code,
                Status = status,
                ParentId = parentId
            };
            
            var result = await _permissionService.GetPagedDtoAsync(pageIndex, pageSize, filter);
            if (result.IsSuccess)
            {
                var (permissions, totalCount) = result.Data;
                var pagedResult = new
                {
                    Permissions = permissions,
                    TotalCount = totalCount,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    TotalPages = (int)Math.Ceiling((double)totalCount / pageSize)
                };
                return ApiResponse<object>.Success(pagedResult);
            }
            return ApiResponse<object>.Fail(result.Message);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.GetPaged异常");
            return ApiResponse<object>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpGet("count")]
    public async Task<ApiResponse<int>> GetCount()
    {
        try
        {
            return await _permissionService.GetCountAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.GetCount异常");
            return ApiResponse<int>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("{permissionId}/assign-role/{roleId}")]
    public async Task<ApiResponse<bool>> AssignRole(Guid permissionId, Guid roleId)
    {
        try
        {
            return await _permissionService.AssignRoleAsync(permissionId, roleId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.AssignRole异常，PermissionId={PermissionId}, RoleId={RoleId}", permissionId, roleId);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    [HttpPost("{permissionId}/remove-role/{roleId}")]
    public async Task<ApiResponse<bool>> RemoveRole(Guid permissionId, Guid roleId)
    {
        try
        {
            return await _permissionService.RemoveRoleAsync(permissionId, roleId);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.RemoveRole异常，PermissionId={PermissionId}, RoleId={RoleId}", permissionId, roleId);
            return ApiResponse<bool>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取权限树形结构 - 前端需要的接口
    /// </summary>
    [HttpGet("tree")]
    public async Task<ApiResponse<IEnumerable<PermissionDto>>> GetPermissionTree()
    {
        try
        {
            return await _permissionService.GetAllDtoAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.GetPermissionTree异常");
            return ApiResponse<IEnumerable<PermissionDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取用户权限
    /// </summary>
    [HttpGet("user/{userId}")]
    public Task<ApiResponse<IEnumerable<PermissionDto>>> GetUserPermissions(Guid userId)
    {
        try
        {
            // 这里应该根据用户权限返回权限列表，暂时返回空列表
            var permissions = new List<PermissionDto>();
            return Task.FromResult(ApiResponse<IEnumerable<PermissionDto>>.Success(permissions, "获取用户权限成功"));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.GetUserPermissions异常，UserId={UserId}", userId);
            return Task.FromResult(ApiResponse<IEnumerable<PermissionDto>>.Fail($"控制器异常: {ex.Message}"));
        }
    }

    /// <summary>
    /// 获取角色权限
    /// </summary>
    [HttpGet("role/{roleId}")]
    public Task<ApiResponse<IEnumerable<PermissionDto>>> GetRolePermissions(Guid roleId)
    {
        try
        {
            // 这里应该根据角色权限返回权限列表，暂时返回空列表
            var permissions = new List<PermissionDto>();
            return Task.FromResult(ApiResponse<IEnumerable<PermissionDto>>.Success(permissions, "获取角色权限成功"));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.GetRolePermissions异常，RoleId={RoleId}", roleId);
            return Task.FromResult(ApiResponse<IEnumerable<PermissionDto>>.Fail($"控制器异常: {ex.Message}"));
        }
    }

    /// <summary>
    /// 获取顶级权限分组
    /// </summary>
    /// <returns>顶级权限列表</returns>
    [HttpGet("top-level")]
    public async Task<ApiResponse<IEnumerable<PermissionDto>>> GetTopLevelPermissions()
    {
        try
        {
            return await _permissionService.GetTopLevelPermissionsAsync();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "PermissionController.GetTopLevelPermissions异常");
            return ApiResponse<IEnumerable<PermissionDto>>.Fail($"控制器异常: {ex.Message}");
        }
    }
} 